package com.sumainfor.common.utlis;

import com.sumainfor.common.entity.ResultTemplateDate;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.wechat.MyX509TrustManager;
import com.sumainfor.common.wechat.WeChatConfig;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.Iterator;
import java.util.Map.Entry;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.net.ConnectException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

/**
 * 功能描述:
 *
 * @Auther: zhlu
 * @Date: 2019/1/25 09:55
 * @Description:
 */
@Log4j2
public class Jsapi_ticketUtil {

    /**
     * 发起https请求并获取结果
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 获取access_token
     *
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public static String getAccessToken(String appid, String appsecret) {
        // 获取公众号access_token的链接
        String access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

        String requestUrl = access_token.replace("APPID", appid).replace("APPSECRET", appsecret);

        JSONObject jsonObject = httpRequest(requestUrl, "GET", null);

        log.info("获取结果");
        log.info("jsonObject"+jsonObject);
        // 如果请求成功
        if (null != jsonObject) {
            try {
                return jsonObject.getString("access_token");
            } catch (JSONException e) {
            }
        }
        return null;
    }


    /**
     * 获取jsapi_ticket
     *
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public static String getJsapiTicket(String accessToken) {
        // 获取公众号jsapi_ticket的链接
        String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
        if (accessToken != null) {
            String requestUrl = jsapi_ticket_url.replace("ACCESS_TOKEN", accessToken);
            JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
            System.out.println(jsonObject);
            // 如果请求成功
            if (null != jsonObject) {
                try {
                    return jsonObject.getString("ticket");
                } catch (JSONException e) {
                }
            }
        } else {
            System.out.println("*****token为空 获取ticket失败******");
        }

        return null;
    }



    public static String getSign(String noncestrs, String jsapi_tickets, String time, String urls){
        String[] arr = new String[] {
                "jsapi_ticket="+jsapi_tickets, "noncestr="+noncestrs, "timestamp="+time, "url="+urls
        };
        Arrays.sort(arr);
        String string1 = null;
        for (int i = 0; i < arr.length; i++) {
            //content.append(arr[i]);
            if(string1 == null){
                string1 = arr[i]+"&";
            }else{
                string1 +=arr[i]+"&";
            }
        }
        string1 = string1.substring(0, string1.length()-1);
        System.out.println(string1);
        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(string1.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return tmpStr;
    }
    /**
     * 将字节数组转换为十六进制字符串
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }


    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     *            *
     * @return
     **/
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
                'b', 'c', 'd', 'e', 'f' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];


        String s = new String(tempArr);
        return s;
    }
    /**
     * 微信模板消息推送
     */
    public static String sendTemplate(String touser, String templateId, String clickurl, String topcolor, JSONObject data) {
        String apd=Jsapi_ticketUtil.getAccessToken(WeChatConfig.APP_ID,WeChatConfig.APP_SECRET);
		/*String tepUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="
				+ apd;*/
        String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+apd;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        System.out.println("tepUrl："+tmpurl);
        System.out.println("apd："+apd);
        HttpPost httpPost = new HttpPost(tmpurl);
        // 装配post请求参数
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("touser", touser);
        json.put("template_id", templateId);
        json.put("url", clickurl);
        json.put("topcolor", topcolor);
        json.put("data", data);
        String resultStr = "发送失败";
        try {
            StringEntity myEntity = new StringEntity(json.toJSONString(), ContentType.APPLICATION_JSON);

            // 设置post求情参数
            httpPost.setEntity(myEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            log.info("httpResponse");
            log.info(httpResponse);
            log.info(httpResponse.getStatusLine().getStatusCode());
            log.info("111111111111111111111111111111111111111111111111");
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 发送成功
                String resutlEntity = EntityUtils.toString(httpResponse.getEntity());
                ResultTemplateDate resultTemplateDate = com.alibaba.fastjson.JSONObject.parseObject(resutlEntity, ResultTemplateDate.class);
                if (resultTemplateDate.getErrcode().equals("40037")) {
                    resultStr = "template_id不正确";
                }
                if (resultTemplateDate.getErrcode().equals("41028")) {
                    resultStr = "form_id不正确，或者过期";
                }
                if (resultTemplateDate.getErrcode().equals("41029")) {
                    resultStr = "form_id已被使用";
                }
                if (resultTemplateDate.getErrcode().equals("41030")) {
                    resultStr = "page不正确";
                }
                if (resultTemplateDate.getErrcode().equals("45009")) {
                    resultStr = "接口调用超过限额（目前默认每个帐号日调用限额为100万）";
                }
                resultStr = "ok";
                return resultStr;
            } else {
                // 发送失败
                return resultStr;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    // 释放资源
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultStr;
    }
}
